from django.db import models
from django.conf import settings
from django.utils import timezone

from uuslug import slugify

User = settings.AUTH_USER_MODEL


class BlogPost(models.Model):
    """Model definition for BlogPost."""
    title = models.CharField(max_length=120)
    slug = models.SlugField(unique=True, blank=True)
    author = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    published_at= models.DateTimeField(blank=True, null=True)
    is_published = models.BooleanField(default=False)


    class Meta:
        """Meta definition for BlogPost."""
        verbose_name = 'BlogPost'
        verbose_name_plural = 'BlogPosts'

    def __str__(self):
        """Unicode representation of BlogPost."""
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)

        if self.is_published:
            if not self.published_at:
                self.published_at = timezone.now()
        else:
            self.published_at = None
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('blog:detail', kwargs={'slug': self.slug})